<template>
  <section class="todoapp">
    <hm-header @add="handleAdd"></hm-header>
    <hm-main
      :list="showList"
      @changeAll="handleAll"
      @del="handleDel"
      @changeState="handleChangeState"
    ></hm-main>
    <hm-footer
      :list="list"
      @clear="handleClear"
      :type="type"
      @changeType="handleType"
    ></hm-footer>
  </section>
</template>

<script>
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todoList")) || [],
      type: "all",
    };
  },
  methods: {
    handleAll(flag){
     this.list.forEach(item=>item.flag = flag)
    },
    handleDel(id) {
      // console.log(id)
      this.list = this.list.filter((item) => item.id !== id);
    },
    handleAdd(value) {
      this.list.unshift({
        id: +new Date(),
        name: value,
        flag: false,
      });
    },
    handleChangeState(flag, id) {
      const obj = this.list.find((item) => item.id === id);
      obj.flag = flag;
    },
    handleClear() {
      console.log(1);
      this.list = this.list.filter((item) => item.flag === false);
    },
    handleType(type) {
      this.type = type;
    },
  },
  computed: {
    showList() {
      if (this.type === "all") {
        return this.list;
      } else if (this.type === "active") {
        return this.list.filter((item) => item.flag === false);
      } else {
        return this.list.filter((item) => item.flag === true);
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newvalue) {
        localStorage.setItem("todoList", JSON.stringify(newvalue));
      },
    },
  },
};
</script>

<style></style>
